package com.varian.redis.aspect;

import com.varian.tool.Func;
import org.springframework.expression.EvaluationContext;
import org.springframework.lang.Nullable;

/**
 * @author ben
 * @since 2024/9/29
 */
public class VarianCacheEvaluationContextFactory {
    public final String RESULT_VARIABLE = "result";
    public static final Object NO_RESULT = new Object();
    public static final Object RESULT_UNAVAILABLE = new Object();

    public EvaluationContext forOperation(VarianCacheContext cacheContext, @Nullable Object result) {
        VarianCacheExpressionRootObject rootObject = new VarianCacheExpressionRootObject(cacheContext.getMethod(), cacheContext.getArgs(), cacheContext.getTarget(), cacheContext.getTarget().getClass());
        VarianCacheEvaluationContext evaluationContext = new VarianCacheEvaluationContext(rootObject, cacheContext.getMethod(), cacheContext.getArgs(), Func.getParameterNameDiscoverer());
        if (result == RESULT_UNAVAILABLE) {
            evaluationContext.addUnavailableVariable(RESULT_VARIABLE);
        }
        else if (result != NO_RESULT) {
            evaluationContext.setVariable(RESULT_VARIABLE, result);
        }
        return evaluationContext;
    }
}
